import 'package:flutter/material.dart';

import 'package:top_foundation/top_foundation.dart';

import 'package:photo_view/photo_view.dart';
import 'package:photo_view/photo_view_gallery.dart';

void gallery(List<GalleryModel> items, {int showIndex = 0}) {
  Get.to(
    () => GalleryPage(
      items: items,
      showIndex: showIndex,
    ),
    transition: Transition.noTransition,
  );
}

class GalleryPage extends StatefulWidget {
  const GalleryPage({
    Key? key,
    required this.items,
    required this.showIndex,
  }) : super(key: key);
  final List<GalleryModel> items;
  final int showIndex;
  @override
  State<GalleryPage> createState() => _GalleryPageState();
}

class _GalleryPageState extends State<GalleryPage> {
  late PageController pageCtrl;
  @override
  void initState() {
    super.initState();
    pageCtrl = PageController(initialPage: widget.showIndex);
  }

  Widget _buildItem(GalleryModel md) {
    if (md.url.isImageFileName) {
      return loadImage(
        url: md.url,
        fit: BoxFit.contain,
      );
    } else {
      return VideoView(
        url: md.url,
        isShow: md.isShow,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    var items = widget.items;
    return Stack(
      children: [
        PhotoViewGallery.builder(
            itemCount: items.length,
            pageController: PageController(initialPage: widget.showIndex),
            onPageChanged: (index) {
              for (var i = 0; i < items.length; i++) {
                items[i].isShow.value = index == i;
              }
            },
            builder: (ctx, index) {
              var item = items[index];
              return PhotoViewGalleryPageOptions.customChild(
                child: _buildItem(item),
                minScale: PhotoViewComputedScale.contained * 0.8,
                maxScale: PhotoViewComputedScale.covered * 1.1,
                initialScale: PhotoViewComputedScale.contained * 0.8,
                heroAttributes: PhotoViewHeroAttributes(
                  tag: item.id,
                ),
              );
            }),
        Positioned(
          left: 0,
          child: SafeArea(
            child: InkWell(
              onTap: () {
                Get.back();
              },
              child: Container(
                width: 40.r,
                height: 40.r,
                alignment: Alignment.center,
                child: const Icon(
                  Icons.close,
                  color: Colors.white,
                ),
              ),
            ),
          ),
        ),
      ],
    );
  }

  @override
  void dispose() {
    super.dispose();
    pageCtrl.dispose();
    for (var element in widget.items) {
      element.dispose();
    }
  }
}
